<script setup>
import { ref,getCurrentInstance } from 'vue'
import axios from "@/utils/request.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from "vue";
import { newsAddService, newsSelectService,newsModifyService,newsDeleteService } from '@/api/news'

import { fileUploadService } from '@/api/file';
import { MdPreview } from 'md-editor-v3';
// import { MDEditor } from 'md-editor-v3';
// import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';

//获取全局变量
const instance = getCurrentInstance();  // 获取当前实例
const $imageUrlPre = instance.appContext.config.globalProperties.$imageUrlPre;


// 分页查询
const newsInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
    selectIds.value = selection.map(item => item.newsId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const titleFuzzy = ref()
const total = ref(0)
const imageUrlList = ref([])

//页面加载的时候发送一次查询请求
onMounted(() => {
    load()
})
const handleCurrentChange = (val) => {
    pageNo.value = val
    load()
}
const handleSizeChange = (val) => {
    pageSize.value = val
    load()
}
//发送分页查询请求（包括搜索功能）
const load = async () => {
    const res = await newsSelectService(
        pageNo.value, pageSize.value, titleFuzzy.value
    )
    if (res.data.status === 'success') {
        newsInfo.value = res.data.data.list
        // 批量下载图片，并更新 imageUrlList
        const coverPaths = newsInfo.value.map(v => v.coverPath);
        // 使用 map 方法生成完整的 URL 数组
        const imageUrls = coverPaths.map(coverPath => $imageUrlPre + coverPath);
        // 更新 newsInfo 中的 filePath 为图片的 URL
        newsInfo.value.forEach((item, index) => {
            item.imageCoverPath = imageUrls[index] || ''; // 如果失败则为空字符串
        });

        total.value = res.data.data.totalCount

        imageUrlList.value = imageUrls
    } else {
        ElMessage.error(res.data.info)
    }
}

/**
 * 添加新闻
 */
//定义模态窗口变量和表格对象
const contentModel = ref(false)
const showAddModal = ref(false)
const newsInfoAddForm = ref({
    title: '',
    coverPath: '',
    newsContent: '',
})
//打开模态窗口
const openAddModal = () => {
    //清空对象内容
    fileList.value = []
    newsInfoAddForm.value = {
        title: '',
        coverPath: '',
        newsContent: '',
    }
    showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleFormModifyRef = ref()
const rules = {
    title: [
        { required: true, message: '新闻标题不能为空', trigger: 'change' },
    ],
    coverPath: [
        { required: true, message: '新闻封面不能为空', trigger: 'blur' },
    ]
}
//上传图片
const handleUploadImage = async (event, insertImage, files) => {
    // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
    const res = await fileUploadService(files[0])
    insertImage({
        url:
            $imageUrlPre + res.data.data,
        desc: '图片描述',
        // width: '200px',
        // height: '200px',
    });
}
/**
 * 展示新闻内容
 */
const showContent = ref(false)
const preview = ref(null)
const currentContent = ref('')
const showContentModal = (content) => {
    showContent.value = true
    currentContent.value = content
}
const fileList = ref()
//文件上传成功处理逻辑
const handleFileUpload = (res, file, fileList) => {
    // fileList.value = fileList
    //将后端返回的文件url赋值给表单中的filePath属性
    newsInfoAddForm.value.coverPath = res.data
}
//修改
const handleModifyFileUpload = (res, file, fileList) => {
    // fileList.value = fileList
    //将后端返回的文件url赋值给表单中的filePath属性
    newsForm.value.coverPath = res.data
}
const handleRemove = () => {
    newsInfoAddForm.value.coverPath = ''
}
const beforeNewsUpload = (rawFile) => {
    if (!rawFile.type.startsWith('image/')) {
        ElMessage.error('上传文件必须是图片!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传图片不能超过 10MB!')
        return false
    }
    return true
}
//发送添加新闻请求
const addNewsInfo = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            const res = await newsAddService(newsInfoAddForm.value)
            if (res.data.status === 'success') {
                await load()
                ElMessage.success('添加新闻成功')
            } else {
                ElMessage.error(res.data.info)
            }
            showAddModal.value = false
        }
    })
}

/**
 * 修改新闻信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改新闻（弹出模态窗口）
//定义模态窗口变量和表格对象
const modifyContentModel = ref(false)
const showModifyModal = ref(false)
const newsForm = ref({
    newsId: '',
    title: '',
    coverPath: '',
    newsContent: '',
})
const openModifyModal = (newsInfo) => {
    //将新闻数据渲染到模态窗口的表格上面
    newsForm.value.newsId = newsInfo.newsId
    newsForm.value.title = newsInfo.title
    newsForm.value.coverPath = newsInfo.coverPath
    newsForm.value.newsContent = newsInfo.newsContent
    //打开模态窗口
    showModifyModal.value = true
}

//发送修改新闻请求
const handleEdit = async () => {
    const res = await newsModifyService(newsForm.value)
    if (res.data.status === 'success') {
        await load()
        showModifyModal.value = false
        ElMessage.success('修改新闻信息成功')
    } else {
        ElMessage.error(res.data.info)
    }
}

/**
 * 删除新闻
 */
const openDeleteModal = (newsId) => {
    ElMessageBox.confirm(
        '确定要删除该新闻吗?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            // const newsIds = Array.of(newsId)
            const res = await newsDeleteService(newsId)
            if (res.data.status === 'success') {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败',
                })
            }
            await load()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
/**
 * 批量删除新闻
 */
const opendeleteAllModal = () => {
    //非空判断
    if (selectIds.value == null) {
        ElMessage.info('未选中任何一名新闻')
        return
    }
    if (selectIds.value != null && selectIds.value.length === 0) {
        ElMessage.info('未选中任何一名新闻')
        return
    }
    //批量删除
    ElMessageBox.confirm(
        '确定要删除所有选中的新闻吗?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await newsDeleteService(selectIds.value)
            if (res.data.status === 'success') {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败',
                })
            }
            load()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const getToken = () => {
    return localStorage.getItem('token')
}
</script>

<template>
    <!--  模态窗口-->
    <!--  修改成员信息模态窗口-->
    <div class="modify-modal" v-show="showModifyModal">
        <div class="modify-form">
            <div class="close-btn" @click="showModifyModal = false">&times;</div>
            <h1 style="text-align: center;font-size: 30px">修改新闻信息</h1>
            <el-form :model="newsForm" ref="ruleFormModifyRef" :rules="rules" label-width="auto"
                style="max-width: 600px;margin: auto;margin-top: 50px" @submit.native.prevent>
                <el-form-item label="新闻标题" prop="title">
                    <el-input v-model="newsForm.title" />
                </el-form-item>
                <el-form-item prop="coverPath" label="封面图片">
                    <el-upload :headers="{ token: getToken() }" :action="axios.defaults.baseURL + '/file/uploadImage'"
                        :on-success="handleModifyFileUpload" :on-remove="handleRemove" list-type="picture" limit="1"
                        :before-upload="beforeNewsUpload" :file-list="fileList">
                        <el-button type="primary" style="margin-left: 100px">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="新闻介绍">
                    <el-button @click="modifyContentModel = true">填写内容</el-button>
                </el-form-item>
                <el-form-item style="float: right">
                    <el-button type="primary" @click="handleEdit(ruleFormModifyRef)">修改</el-button>
                    <el-button @click="showAddModal = false">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 修改新闻介绍模态窗口 -->
        <el-dialog v-model="modifyContentModel" fullscreen top="40vh" width="70%" draggable>
            <span>新闻介绍</span>
            <template #footer>
                <div>
                    <v-md-editor v-model="newsForm.newsContent" height="400px" :include-level="[1, 2, 3, 4]"
                        :disabled-menus="[]" @upload-image="handleUploadImage" />
                </div>
                <div class="dialog-footer">
                    <el-button @click="modifyContentModel = false">取消</el-button>
                    <el-button type="primary" @click="modifyContentModel = false">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <!--  添加新闻模态窗口-->
    <div class="modify-modal" v-show="showAddModal">
        <div class="modify-form">
            <div class="close-btn" @click="showAddModal = false">&times;</div>
            <h1 style="text-align: center;font-size: 30px">新闻封面</h1>
            <el-form :model="newsInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
                style="max-width: 600px;margin: auto;margin-top: 50px">
                <el-form-item label="新闻标题" prop="title">
                    <el-input v-model="newsInfoAddForm.title" />
                </el-form-item>
                <el-form-item prop="coverPath" label="封面图片">
                    <el-upload :headers="{ token: getToken() }" :action="axios.defaults.baseURL + '/file/uploadImage'"
                        :on-success="handleFileUpload" :on-remove="handleRemove" list-type="picture" limit="1"
                        :before-upload="beforeNewsUpload" :file-list="fileList">
                        <el-button type="primary" style="margin-left: 100px">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="新闻介绍">
                    <el-button @click="contentModel = true">填写内容</el-button>
                </el-form-item>
                <el-form-item style="float: right">
                    <el-button type="primary" @click="addNewsInfo(ruleFormRef)">添加</el-button>
                    <el-button @click="showAddModal = false">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 填写新闻介绍模态窗口 -->
        <el-dialog v-model="contentModel" fullscreen top="40vh" width="70%" draggable>
            <span>新闻内容</span>
            <template #footer>
                <div>
                    <v-md-editor v-model="newsInfoAddForm.newsContent" height="400px" :include-level="[1, 2, 3, 4]"
                        :disabled-menus="[]" @upload-image="handleUploadImage" />
                </div>
                <div class="dialog-footer">
                    <el-button @click="contentModel = false">取消</el-button>
                    <el-button type="primary" @click="contentModel = false">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <!--    展示题目内容模态窗口-->
    <el-dialog v-model="showContent" title="新闻内容" width="800">

        <div style="height: 500px;">
            <span style="width: 100% !important;display: block;float: left;height: 500px;overflow-y: auto;">
                <MdPreview style="border: 1px solid;" :modelValue="currentContent">
                </MdPreview>
                <!-- <v-md-editor :model-value="currentIntroduction" mode="preview" ref="preview"></v-md-editor> -->
            </span>


        </div>
    </el-dialog>

    <div>
        <!--    功能按钮-->
        <el-card style="width: 34%;margin-bottom: 30px;float: left">
            <el-button @click="openAddModal" type="primary">添加新闻</el-button>
        </el-card>
        <!--    搜索框-->
        <el-card class="member-search">
            <span style="margin-left: 10px">
                <h2>新闻标题：</h2>
            </span>
            <input v-model="titleFuzzy" @keyup.enter.native="load">
            <el-button type="warning" @click="load">搜索</el-button>
        </el-card>
    </div>
    <div>
        <el-table ref="multipleTableRef" :data="newsInfo" stripe style="width: 100%;margin-top: 30px"
            @selection-change="handleSelectionChange">
            <el-table-column width="55" />
            <el-table-column property="title" label="新闻标题" width="250" />
            <el-table-column property="coverPath" label="封面" width="250">
                <template #default="scope">
                    <el-image style="width: 70px;height: 70px" fit="cover" preview-teleported
                        :preview-src-list="imageUrlList" :initial-index="scope.$index" :src="scope.row.imageCoverPath"
                        alt="新闻封面" />
                </template>
            </el-table-column>
            <el-table-column property="createTime" label="创建时间" />
            <el-table-column property="updateTime" label="修改时间" />
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button size="small" type="success" @click="showContentModal(scope.row.newsContent)">
                        详情
                    </el-button>
                    <el-button size="small" type="info" @click="openModifyModal(scope.row)">
                        修改
                    </el-button>
                    <el-button size="small" type="danger" @click="openDeleteModal(scope.row.newsId)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--    分页组件-->
        <el-card style="margin-top: 20px;float: right;">
            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
                    size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @current-change="handleCurrentChange" @size-change="handleSizeChange" />
            </div>
        </el-card>

    </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal {
    position: fixed;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: black;
    opacity: 1;
}

/*模态窗口表格样式*/
.modify-form {
    background-color: #ffffff;
    margin: 5% auto;
    /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    z-index: 10;
    border-radius: 10%;
    width: 30%;
    /* Could be more or less, depending on screen size */
}

.close-btn {
    cursor: pointer;
    color: #000000;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

/*搜索样式*/
.member-search {
    width: 64%;
    float: right
}

.member-search span {
    float: left;
}

.member-search input {
    float: left;
    height: 25px;
    border: solid 2px;
    margin-top: 2px;
}

/*表头样式*/
:deep() th.el-table__cell {
    color: black;
    font-size: 15px;
}
</style>
